package demo4;

import java.util.HashMap;

class LRUCache {
    
    private class Node{
        private int key;
        private int val;
        private Node next;
        private Node prev;
        public Node(int key,int val){
            this.key = key;
            this.val = val;
        }
    }

    private HashMap<Integer,Node> map = new HashMap<>();
    private int capacity =0;
    private Node head,tail;
    private int size =0;

    public LRUCache(int capacity) {
        this.size =0;
        this.capacity = capacity;
        head = new Node(0,0);
        tail = new Node(0,0);
        head.next = tail;
        tail.prev = head;
    }
    
    public int get(int key) {
        Node node = map.get(key);
        if(node==null){
            return -1;
        }
        //存在的情况
        addToHead(node);
        return node.val;
    }
    
    private void addFirstNode(Node node){
        node.prev = head;
        node.next = head.next;
        head.next.prev = node;
        head.next = node;
    }

    private void removeNode(Node node){
        node.prev.next = node.next;
        node.next.prev = node.prev;
    }

    private void addToHead(Node node){
        removeNode(node);
        addFirstNode(node);
    }

    public void put(int key, int value) {
        Node node = map.get(key);
        if(node==null){
            //第一次出现的情况
            Node newNode = new Node(key,value);
            map.put(key,newNode);

        }
    }



}